package net.crazyadam.activity;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.TextView;
import net.crazyadam.R;
import net.crazyadam.audio.Constant;
import net.crazyadam.audio.DopplerPlayer;
import net.crazyadam.network.PacketManager;

import java.util.Collections;
import java.util.Set;

public class Player extends Activity {
    private DopplerPlayer player;
    private PacketManager pm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audio);
        //找到声音文件
        player = new DopplerPlayer(this, R.raw.audio18k);
        //播放声音
        player.start();
        pm = new PacketManager(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        pm.send(Constant.START); //发送主动邀请
        TextView text = (TextView) findViewById(R.id.text);
        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        text.setText("现在可以朝指定的人挥动了～挥动后退出即结束");
    }

    @Override
    protected void onPause() {
        pm.send(Constant.STOP);//发送结束请求
        TextView text = (TextView) findViewById(R.id.text);
        text.setText("等着她们把数据传回來哦～");
        pm.toReceive();//等待返回数据
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        Set<String> results = pm.getResults();
        if (0 < results.size()) {
            String max = Collections.max(results);//取出结果中最大值
            String min = Collections.min(results);//取出结果中最小值
            editor.putString(Constant.RESULT, max + "-->" + min);
        }
        editor.commit();
        //停止声音播放
        player.stop();
        super.onPause();
    }
}

